'use strict';

const { Service } = require('egg');
class AdminService extends Service {
  async selectAll() { // 查询所有管理员
    const data = await this.app.model.Admin.find({}); // 执行mongoose的查询语句
    return data;
  }
  async register(adminObj) { // 管理员注册
    const allAdmin = await this.app.model.Admin.find({ adminName: adminObj.adminName });
    console.log(allAdmin);
    if (allAdmin.length === 0) {
      const model = new this.app.model.Admin(adminObj);
      await model.save();
      return { code: 200, data: model };
    } else {
      return { code: 501, msg: '用户已存在' };
      // ctx.body = { coed: 501, msg: '用户已存在,请更换用户名' };
    }
  }
  async login(adminObj) { // 管理员登录
    const data = await this.app.model.Admin.find({ adminName: adminObj.adminName, adminPwd: adminObj.adminPwd });
    if (data.length === 0) {
      // ctx.body = { coed: 501, msg: '缺少必填项;密码不能为空' };
      return { code: 501, msg: '用户名或密码错误' };
    } else {
      return { code: 200, msg: data[0] };
      // return data;
    }
  }
  // 管理员修改个人信息，包括密码
  async update(newAdminObje) { // 根据管理员用户进行查询修改
    const data = await this.app.model.Admin.update({ adminName: newAdminObje.adminName }, { $set: { adminPwd: newAdminObje.adminPwd, nickname: newAdminObje.nickname, adminPortrait: newAdminObje.adminPortrait, realName: newAdminObje.realName, adminSex: newAdminObje.adminSex, adminAge: newAdminObje.adminAge, adminPhone: newAdminObje.adminPhone } });
    if (data.n >= 1) {
      return { code: 200, data };
    } else {
      return { code: 501, msg: '修改失败' };
    }
  }
  // 根据管理员用户名查找
  async findByAdminName(adminName) {
    const data = await this.app.model.Admin.find({ adminName }); // 执行mongoose的查询语句
    if (data.length === 0) {
      return { code: 501, msg: '查找失败' };
    } else {
      return data[0];
    }
  }

}
module.exports = AdminService;
